import CreateModal from '@/pages/Admin/Generator/components/CreateModal';
import UpdateModal from '@/pages/Admin/Generator/components/UpdateModal';
import {
  deleteGeneratorUsingPost,
  listGeneratorByPageUsingPost,
} from '@/services/backend/generatorController';
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import ProField from '@ant-design/pro-field/lib';
import '@umijs/max';
import { Button, Image, message, Modal, Select, Space, Tag, Typography } from 'antd';
import React, { useRef, useState } from 'react';

/**
 * 代码生成器管理页面
 *
 * @constructor
 */
const GeneratorAdminPage: React.FC = () => {
  // 是否显示新建窗口
  const [createModalVisible, setCreateModalVisible] = useState<boolean>(false);
  // 是否显示更新窗口
  const [updateModalVisible, setUpdateModalVisible] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  // 当前代码生成器点击的数据
  const [currentRow, setCurrentRow] = useState<API.Generator>();

  /**
   * 删除节点
   *
   * @param row
   */
  const handleDelete = async (row: API.Generator) => {
    // 使用Modal.confirm展示确认对话框
    Modal.confirm({
      title: '确认删除',
      content: '你确定要删除这条记录吗？这个操作是不可逆的',
      okText: '确认',
      okType: 'danger',
      centered: true,
      cancelText: '取消',
      onOk: async () => {
        // 用户确认删除操作
        const hide = message.loading('正在删除');
        if (!row) return true;
        try {
          await deleteGeneratorUsingPost({
            id: row.id as any,
          });
          hide();
          message.success('删除成功');
          actionRef?.current?.reload();
          return true;
        } catch (error: any) {
          hide();
          message.error('删除失败，' + error.message);
          return false;
        }
      },
      onCancel() {
        // 用户取消删除操作
        console.log('取消删除');
      },
    });
  };

  // @ts-ignore
  /**
   * 表格列配置
   */
  const columns: ProColumns<API.Generator>[] = [
    {
      title: '序号',
      dataIndex: 'id',
      valueType: 'indexBorder',
      hideInForm: true,
      width: 48,
      align: 'center',
      render: (_, record, index) => (
        <Tag color="blue" style={{ borderRadius: '20px' }}>
          {index + 1}
        </Tag>
      ),
    },
    {
      title: '名称',
      dataIndex: 'name',
      valueType: 'text',
      align: 'center',
    },
    {
      title: '描述',
      dataIndex: 'description',
      valueType: 'textarea',
      ellipsis: true,
      hideInSearch: true,
      align: 'center',
    },
    {
      title: '基础包',
      dataIndex: 'basePackage',
      valueType: 'text',
      hideInSearch: true,
      align: 'center',
    },
    {
      title: '作者',
      dataIndex: 'author',
      valueType: 'text',
      align: 'center',
    },
    {
      title: '版本',
      dataIndex: 'version',
      valueType: 'text',
      hideInSearch: true,
      align: 'center',
    },
    {
      title: '标签',
      dataIndex: 'tags',
      valueType: 'select',
      align: 'center',
      renderFormItem: (schema) => {
        const { fieldProps } = schema;
        // @ts-ignore
        return <Select mode="tags" {...fieldProps} />;
      },
      render(_, record) {
        if (!record.tags) {
          return <></>;
        }
        return JSON.parse(record.tags).map((tag: string) => {
          return <Tag key={tag}>{tag}</Tag>;
        });
      },
    },
    {
      title: '图片',
      dataIndex: 'picture',
      valueType: 'image',
      render: (_, record) => (
        <div>
          <Image src={record.picture} width={80} height={60} />
        </div>
      ),
      hideInSearch: true,
      align: 'center',
    },
    {
      title: '文件配置',
      dataIndex: 'fileConfig',
      hideInSearch: true,
      valueType: 'jsonCode',
      hideInTable: true,
      render(_, record) {
        if (!record.fileConfig) {
          return '{}';
        }
        return (
          <ProField text={JSON.stringify(record.fileConfig)} mode="read" valueType="jsonCode" />
        );
      },
    },
    {
      title: '模型配置',
      dataIndex: 'modelConfig',
      valueType: 'jsonCode',
      hideInSearch: true,
      hideInTable: true,
      render(_, record) {
        if (!record.modelConfig) {
          return '{}';
        }
        return (
          <ProField text={JSON.stringify(record.modelConfig)} mode="read" valueType="jsonCode" />
        );
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      valueType: 'select',
      hideInForm: true,
      valueEnum: {
        0: { text: <Tag color="success">正常</Tag>, status: 'Success' },
        1: { text: <Tag color="error">关闭</Tag>, status: 'Error' },
      },
      align: 'center',
    },
    {
      title: '产物路径',
      dataIndex: 'distPath',
      valueType: 'text',
      ellipsis: true,
      hideInSearch: true,
      hideInForm: true,
      align: 'center',
    },
    {
      title: '版本控制',
      dataIndex: 'versionControl',
      valueType: 'radio',
      hideInSearch: true,
      valueEnum: {
        1: {
          text: <Tag color="success">开启</Tag>,
          status: 'Success',
        },
        0: {
          text: <Tag color="warning">关闭</Tag>,
          status: 'Default',
        },
      },
      align: 'center',
    },
    {
      title: '强制交互',
      dataIndex: 'forcedInteractive',
      valueType: 'radio',
      hideInSearch: true,
      valueEnum: {
        1: {
          text: <Tag color="success">开启</Tag>,
          status: 'Success',
        },
        0: {
          text: <Tag color="warning">关闭</Tag>,
          status: 'Default',
        },
      },
      align: 'center',
    },
    {
      title: '创建用户',
      dataIndex: 'userId',
      valueType: 'text',
      hideInForm: true,
      hideInTable: true,
      hideInSearch: true,
      align: 'center',
    },
    {
      title: '创建时间',
      sorter: true,
      dataIndex: 'createTime',
      valueType: 'dateTime',
      hideInSearch: true,
      hideInForm: true,
      align: 'center',
    },
    {
      title: '更新时间',
      sorter: true,
      dataIndex: 'updateTime',
      valueType: 'dateTime',
      hideInSearch: true,
      hideInForm: true,
      align: 'center',
    },
    {
      title: '操作',
      align: 'center',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <Space size="middle">
          <Typography.Link
            onClick={() => {
              setCurrentRow(record);
              setUpdateModalVisible(true);
            }}
          >
            修改
          </Typography.Link>
          <Typography.Link type="danger" onClick={() => handleDelete(record)}>
            删除
          </Typography.Link>
        </Space>
      ),
    },
  ];
  return (
    <div className="generator-admin-page">
      <Typography.Title level={4} style={{ marginBottom: 16 }}>
        生成器管理
      </Typography.Title>
      <ProTable<API.Generator>
        headerTitle={'生成器列表'}
        actionRef={actionRef}
        rowKey="key"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              setCreateModalVisible(true);
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
        ]}
        request={async (params, sort, filter) => {
          const sortField = Object.keys(sort)?.[0];
          const sortOrder = sort?.[sortField] ?? undefined;

          const { data, code } = await listGeneratorByPageUsingPost({
            ...params,
            sortField,
            sortOrder,
            ...filter,
          } as API.GeneratorQueryRequest);

          return {
            success: code === 0,
            data: data?.records || [],
            total: Number(data?.total) || 0,
          };
        }}
        columns={columns}
      />
      <CreateModal
        visible={createModalVisible}
        columns={columns}
        onSubmit={() => {
          setCreateModalVisible(false);
          actionRef.current?.reload();
        }}
        onCancel={() => {
          setCreateModalVisible(false);
        }}
      />
      <UpdateModal
        visible={updateModalVisible}
        columns={columns}
        oldData={currentRow}
        onSubmit={() => {
          setUpdateModalVisible(false);
          setCurrentRow(undefined);
          actionRef.current?.reload();
        }}
        onCancel={() => {
          setUpdateModalVisible(false);
        }}
      />
    </div>
  );
};
export default GeneratorAdminPage;
